<template>
  <view class="login-container" :style="{ paddingTop: navHeight + 'px' }">
    <!-- 顶部logo和标题（横向排列，居中） -->
    <view class="login-header-row">
      <image class="login-logo" src="/static/logo.png" mode="widthFix"></image>
      <view class="login-title">欢迎登录私小理</view>
    </view>
    <!-- 输入框区域 -->
    <view class="login-form">
      <!-- 手机号输入框 -->
      <view class="login-input-group">
        <image class="login-input-icon" src="/static/phone.png" mode="aspectFit"></image>
        <input class="login-input" type="tel" maxlength="20" v-model="loginInfo.username" placeholder="请输入手机号"
          placeholder-class="input-placeholder" @focus="fixIosScroll" />
        <image v-if="loginInfo.username" class="clear-icon" src="/static/clear.png" mode="aspectFit" @tap="clearPhone">
        </image>
      </view>
      <!-- 验证码输入框 -->
      <view class="login-input-group">
        <image class="login-input-icon" src="/static/Invitation_code.png" mode="aspectFit"></image>
        <input class="login-input" type="number" v-model="loginInfo.password" placeholder="请输入验证码"
          placeholder-class="input-placeholder" @focus="fixIosScroll" />
        <view class="login-code-btn" :class="{ disabled: !canGetCode }" @tap.stop="canGetCode ? getCode() : null">{{
          tips
        }}</view>
      </view>
      <!-- 邀请码输入框 -->
      <view class="login-input-group">
        <image class="login-input-icon" src="/static/login_code.png" mode="aspectFit"></image>
        <input class="login-input" type="number" v-model="loginInfo.invite" placeholder="请输入邀请码（非必填）"
          placeholder-class="input-placeholder" @focus="fixIosScroll" />
      </view>
    </view>
    <!-- 登录按钮 -->
    <view class="login-btn-wrapper">
      <button class="login-btn" @click="startLogin">确认登录</button>
    </view>
    <!-- 协议勾选区 -->
    <view class="login-protocol">
      <image :src="protocolChecked ? '/static/a2.png' : '/static/a1.png'" class="protocol-checkbox-img"
        @click="protocolChecked = !protocolChecked" />
      <text class="protocol-text">
        <span style="color: #7C7B76;">已阅读并同意</span>
        <span style="color: #ffffff;" @click="goToProtocol('user')">《用户协议》</span>
        <span style="color: #7C7B76;">和</span>
        <span style="color: #ffffff;" @click="goToProtocol('privacy')">《隐私政策》</span>
      </text>
    </view>
    <!-- 验证码倒计时组件 -->
    <tn-verification-code ref="code" uniqueKey="login-demo-1" :seconds="60" @change="codeChange" />

    <!-- 协议确认弹窗 -->
    <view v-if="showProtocolModal" class="protocol-modal-overlay" @click="hideProtocolModal">
      <view class="protocol-modal" @click.stop>
        <view class="protocol-modal-title">用户协议及隐私保护政策</view>
        <view class="protocol-modal-content">
          <text class="protocol-modal-text">
            我已阅读并同意
            <text class="protocol-link" @click="goToProtocol('user')">用户协议</text>、
            <text class="protocol-link" @click="goToProtocol('privacy')">隐私政策</text>
          </text>
        </view>
        <view class="protocol-modal-buttons">
          <view class="protocol-modal-cancel" @click="hideProtocolModal">取消</view>
          <view class="protocol-modal-confirm" @click="agreeAndLogin">同意并登录</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import template_page_mixin from '@/libs/mixin/template_page_mixin.js'
export default {
  name: 'templateLogin',
  mixins: [template_page_mixin],
  data() {
    return {
      // 当前选中的模式
      currentModeIndex: 0,
      // 模式选中滑块
      modeSliderStyle: {
        left: 0
      },
      // 是否显示密码
      showPassword: false,
      loginInfo: {
        username: '',
        password: '',
      },
      // 倒计时提示文字
      tips: '获取验证码',
      phone: '',
      show: false,
      isiosshow: false,
      protocolChecked: false, // 协议勾选状态，默认未选中
      showProtocolModal: false, // 控制协议确认弹窗显示
      navHeight: '', //整体顶部导航栏的高度
      statusBarHeight: '', //状态栏高度
    }
  },
  onLoad() {
    let {
      statusBarHeight,
      system
    } = uni.getSystemInfoSync();
    this.statusBarHeight = statusBarHeight;
    this.navHeight = statusBarHeight + (system.indexOf("iOS") > -1 ? 44 : 48);
    //#ifdef APP-PLUS
    const that = this
    uni.preLogin({
      provider: 'univerify',
      success() {
        //预登录成功
        that.show = true
      },
      fail(res) {
        // 预登录失败
        that.show = false
      }
    });
    uni.getSystemInfo({
      success: function (res) {
        vm.platform = res.platform; //ios  or android
        if (res.platform == "ios") {
          uni.request({
            url: "https://api.cycyai.com/module.php?m=aichat_api&a=clear&ajax=1",
            method: "GET",
            data: {
              appVersionType: 2
            },
            dataType: 'json',
            success: (res) => {
              if (res.data.data.data[0].ioslogin == 1) {
                // 苹果演示账户
                this.isiosshow = true;
              }
            },
            complete: () => {
              uni.hideLoading();
            }
          });
        }
      }
    });
    //#endif
  },
  methods: {
    getPhoneNumber(e) {
      // #ifdef MP-WEIXIN
      // 登录
      uni.showLoading({
        title: '登录中...',
        mask: false
      });
      var that = this;
      uni.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          uni.hideLoading();

          uni.getUserInfo({
            success: (info) => {
              uni.request({
                url: "https://api.cycyai.com/index.php?m=login&a=getUnionid&ajax=1",
                method: 'GET',
                data: {
                  'code': e.detail.code,
                },
                success: function (res2) {
                  var data = JSON.parse(res2.data.data);
                  let formData = {
                    telephone: data.phone_info.phoneNumber,
                  };
                  that.$Request.postApi(
                    "/index.php?m=login&a=loginSave&ajax=1",
                    formData).then((res) => {
                      if (res.error == 0) {
                        uni.hideLoading()
                        uni.setStorageSync(
                          'loginToken', res.data
                          .token)
                        uni.setStorageSync(
                          'loginRefreshToken',
                          res.data.refresh_token)
                        uni.setStorageSync('userInfo',
                          res.data.user)

                        // 检查用户是否已经填写过资料或跳过资料填写
                        const userInfo = res.data.user;
                        const zodiac = userInfo.zodiac;
                        const hasSkippedProfile = userInfo.has_skipped_profile;



                        if ((zodiac === "" || zodiac === null || zodiac === undefined) && !hasSkippedProfile) {
                          // zodiac为空且未跳过资料填写，说明用户首次登录，需要跳转到login2页面填写资料
                          uni.reLaunch({
                            url: '/minePages/login2'
                          });
                        } else {
                          // zodiac已有值或已跳过资料填写，检查是否已选择私人秘书
                          const botAppSecret = userInfo.bot_appsecret;

                          if (botAppSecret && botAppSecret !== "" && botAppSecret !== null && botAppSecret !== undefined) {
                            // bot_appsecret有值，说明用户已经选择了私人秘书，直接跳转到主页
                            uni.reLaunch({
                              url: '/pages/galaxyBrand/index'
                            });
                          } else {
                            // bot_appsecret为空，需要跳转到login3页面选择私人秘书
                            uni.reLaunch({
                              url: '/minePages/login3'
                            });
                          }
                        }
                      } else {
                        uni.showModal({
                          showCancel: false,
                          title: '登录失败',
                          content: res
                            .message,
                        });
                      }
                    });
                },
              });
            }
          });
        }
      });
      // #endif

      // #ifdef APP-PLUS

      var that = this;

      uni.login({
        provider: 'weixin',
        success: function (loginRes) {
          // 获取用户信息
          uni.getUserInfo({
            provider: 'weixin',
            success: function (infoRes) {
              var nickName = infoRes.userInfo.nickName;
              var avatarUrl = infoRes.userInfo.avatarUrl;
              var unionid = infoRes.userInfo.unionId;
              that.thirdlogin(unionid, nickName, avatarUrl, 2, 2);

            }
          });
        }
      });

      // #endif
    },
    // 跳转
    tn(e) {
      uni.navigateTo({
        url: e,
      });
    },
    // 切换模式
    modeSwitch(index) {
      this.currentModeIndex = index
      this.showPassword = false
    },
    // 获取验证码
    getCode() {
      if (this.$refs.code.canGetCode) {
        let formData = {
          telephone: this.loginInfo.username,
        };
        this.$Request.postApi("/bot/api/agentsendsms", formData).then((res) => {
          if (res.status == 1) { }
        });
        this.$t.message.loading('正在获取验证码')
        setTimeout(() => {
          this.$t.message.closeLoading()
          this.$t.message.toast('验证码已经发送')
          // 通知组件开始计时
          this.$refs.code.start()
        }, 2000)
      } else {
        this.$t.message.toast(this.$refs.code.secNum + '秒后再重试')
      }
    },
    // 登录
    startLogin() {
      // uni.navigateTo({
      //   url: '/minePages/login2'
      // });
      const phoneReg = /^1[3-9]\d{9}$/;
      if (!this.loginInfo.username) {
        uni.showToast({
          title: '手机号不能为空',
          icon: 'none'
        });
        return;
      }
      if (!phoneReg.test(this.loginInfo.username)) {
        uni.showToast({
          title: '请输入正确的手机号',
          icon: 'none'
        });
        return;
      }
      if (!this.loginInfo.password) {
        uni.showToast({
          title: '验证码不能为空',
          icon: 'none'
        });
        return;
      }
      if (!/^\d{4}$/.test(this.loginInfo.password)) {
        uni.showToast({
          title: '您输入的验证码有误',
          icon: 'none'
        });
        return;
      }
      if (!this.protocolChecked) {
        this.showProtocolModal = true;
        return;
      }
      let formData = {
        telephone: this.loginInfo.username,
        yzm: this.loginInfo.password,
        invitecode: this.loginInfo.invite || ''
      };
      this.$Request.postApi("/bot/api/agentsmslogin", formData).then((res) => {
        if (res.status == 1) {
          uni.hideLoading();
          uni.setStorageSync('userInfo', res.data);
          // 检查用户是否已经填写过资料
          const zodiac = res.data.zodiac;
          // const hasSkippedProfile = res.data.has_skipped_profile;
          if (zodiac === "" || zodiac === null || zodiac === undefined) {
            // zodiac为空且未跳过资料填写，说明用户首次登录，需要跳转到login2页面填写资料
            uni.reLaunch({
              url: '/minePages/login2'
            });
          } else {
            // uni.reLaunch({
            //     url: '/minePages/login3'
            //   });
            // zodiac已有值，检查是否已选择私人秘书
            const botAppSecret = res.data.bot_appsecret;
            if (botAppSecret && botAppSecret !== "" && botAppSecret !== null && botAppSecret !== undefined) {
              // bot_appsecret有值，说明用户已经选择了私人秘书，直接跳转到主页
              uni.reLaunch({
                url: '/pages/index'
              });
            } else {
              // bot_appsecret为空，需要跳转到login3页面选择私人秘书
              uni.reLaunch({
                url: '/minePages/login3'
              });
            }
          }
        } else {
          uni.hideLoading();
          uni.showModal({
            showCancel: false,
            title: '登录失败',
            content: res.message,
          });
        }
      }).catch((err) => {
        console.error('登录请求失败:', err);
        uni.hideLoading();
        uni.showModal({
          showCancel: false,
          title: '登录失败',
          content: '网络请求失败，请检查网络连接后重试',
        });
      });
    },
    // 获取验证码倒计时被修改
    codeChange(event) {
      this.tips = event
    },
    clearPhone() {
      this.loginInfo.username = '';
    },
    fixIosScroll() {
      // #ifdef APP-PLUS
      const sys = uni.getSystemInfoSync();
      if (sys.platform === 'ios') {
        setTimeout(() => {
          window.scrollTo(0, 0);
          document.documentElement.scrollTop = 0;
          document.body.scrollTop = 0;
        }, 100);
      }
      // #endif
    },
    // 跳转到协议页面
    goToProtocol(type) {
      let url = '/minePages/content';
      if (type === 'user') {
        // 跳转到用户协议
        url += '?type=agreement';
      } else if (type === 'privacy') {
        // 跳转到隐私政策
        url += '?type=privacy';
      }
      uni.navigateTo({
        url: url
      });
    },
    // 隐藏协议确认弹窗
    hideProtocolModal() {
      this.showProtocolModal = false;
    },
    // 同意协议并登录
    agreeAndLogin() {
      this.protocolChecked = true;
      this.showProtocolModal = false;
      // 重新执行登录逻辑
      this.startLogin();
    }
  },
  computed: {
    canGetCode() {
      const phoneReg = /^1[3-9]\d{9}$/;
      return phoneReg.test(this.loginInfo.username);
    }
  },
  onShow() {
    // #ifdef APP-PLUS
    // 兼容iOS和Android，强制设置软键盘弹出模式为 adjustResize
    if (typeof plus !== 'undefined' && plus.webview && plus.webview.currentWebview) {
      plus.webview.currentWebview().setStyle({
        softinputMode: 'adjustResize'
      });
    }
    // #endif
  }
}
</script>

<style lang="scss" scoped>
page {
  background-color: #100D05;
}

.login-container {
  min-height: 100vh;
  height: auto;
  // background-color: #100D05;
  background-image: url('/static/login/login1.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  padding-bottom: 80rpx;
}

.login-header-row {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
  margin-bottom: 60rpx;
  width: 100%;
  margin-top: 80rpx;
}

.login-logo {
  width: 60rpx;
  height: 60rpx;
  margin-right: 18rpx;
}

.login-title {
  color: #fff;
  font-size: 40rpx;
  font-weight: bold;
  margin-bottom: 0;
  line-height: 60rpx;
}

.login-form {
  width: 626.92rpx;
  max-width: 626.92rpx;
  display: flex;
  flex-direction: column;
  gap: 32rpx;
  margin-bottom: 48rpx;
  margin-left: 61.54rpx;
  margin-right: 61.54rpx;
  margin-top: auto;
}

.login-input-group {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  // background: rgba(35, 35, 35, 0.6);
  border-radius: 42.31rpx;
  padding: 0 32rpx;
  height: 84.62rpx;
  width: 100%;
  margin-bottom: 0;
  position: relative;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.login-input-icon {
  width: 36rpx;
  height: 36rpx;
  margin-right: 18rpx;
  opacity: 0.8;
}

// 文字输入样式
.login-input {
  flex: 1;
  background: transparent;
  border: none;
  outline: none;
  color: rgba(0, 0, 0, 1);
  font-size: 30rpx;
  height: 84.62rpx;
}

.login-code-btn {
  margin-left: 12rpx;
  padding: 0 24rpx;
  height: 56rpx;
  line-height: 56rpx;
  color: #fff;
  border-radius: 22rpx;
  font-size: 26rpx;
  background: linear-gradient(135deg, rgba(73, 102, 241, 0.7), rgba(59, 130, 246, 0.7));
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.2);
}

.login-btn-wrapper {
  width: 626.92rpx;
  max-width: 626.92rpx;
  // margin: 32rpx 0 0 0;
}

.login-btn {
  width: 100%;
  height: 84.62rpx;
  background: rgba(59, 130, 246, 0.6);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  color: #fff;
  font-size: 34rpx;
  font-weight: bold;
  border: none;
  border-radius: 42.31rpx;
  box-shadow: 0 4rpx 24rpx 0 rgba(59, 130, 246, 0.3);
  backdrop-filter: blur(5px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  justify-content: center;
}

.login-btn:active {
  opacity: 0.8;
  transform: scale(0.98);
}

.login-protocol {
  margin-top: 32rpx;
  font-size: 23rpx;
  width: 626.92rpx;
  max-width: 626.92rpx;
  display: flex;
  align-items: center;
  margin-left: 61.54rpx;
  padding-left: 0;
  text-align: left;
  margin-bottom: 30rpx;
}

.protocol-checkbox-img {
  width: 32rpx;
  height: 32rpx;
  margin-right: 12rpx;
}

.protocol-text {
  display: flex;
  align-items: center;
  line-height: 32rpx;

  span {

    &:nth-child(2),
    &:nth-child(4) {
      // 用户协议和隐私政策文字样式
      cursor: pointer;
      // text-decoration: underline;
      transition: opacity 0.2s ease;

      &:active {
        opacity: 0.7;
      }
    }
  }
}

.input-placeholder {
  color: rgba(0, 0, 0, 1);
  font-size: 30rpx;
}

.login-code-btn.disabled {
  background: rgba(59, 130, 246, 0.6) !important;
  color: rgba(255, 255, 255, 0.5) !important;
  cursor: not-allowed;
  pointer-events: none;
}

.clear-icon {
  width: 38.46rpx;
  height: 38.46rpx;
  margin-left: 12rpx;
}

/* 协议确认弹窗样式 */
.protocol-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 0 60rpx;
}

.protocol-modal {
  background-color: #ffffff;
  border-radius: 24rpx;
  width: 100%;
  max-width: 560rpx;
  padding: 60rpx 40rpx 40rpx 40rpx;
  box-shadow: 0 8rpx 40rpx rgba(0, 0, 0, 0.15);
  position: relative;
}

.protocol-modal-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #000000;
  text-align: center;
  margin-bottom: 40rpx;
  line-height: 1.4;
}

.protocol-modal-content {
  margin-bottom: 50rpx;
}

.protocol-modal-text {
  font-size: 28rpx;
  color: #666666;
  line-height: 1.6;
  text-align: center;
  display: block;
}

.protocol-link {
  color: #3B82F6;
  text-decoration: none;
}

.protocol-modal-buttons {
  display: flex;
  gap: 24rpx;
}

.protocol-modal-cancel {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  color: #666666;
  background-color: #F5F5F5;
  border-radius: 44rpx;
  transition: all 0.2s ease;
}

.protocol-modal-cancel:active {
  opacity: 0.8;
  transform: scale(0.98);
}

.protocol-modal-confirm {
  flex: 1;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  font-size: 32rpx;
  color: #ffffff;
  background: rgba(59, 130, 246);
  border-radius: 44rpx;
  transition: all 0.2s ease;
}

.protocol-modal-confirm:active {
  opacity: 0.8;
  transform: scale(0.98);
}
</style>